<template>
  <div class="_wz_transportVehicleAdd">
    <Form ref="formAdd" :model="formData" label-position="right" :label-width="120" :rules="ruleValidate" inline>
      <Card dis-hover :bordered="true" style="margin:0 0 10px;">
        <p slot="title">基本信息</p>
        <FormItem label="自编号" prop="customNo">
          <i-input v-model="formData.customNo" placeholder="请填写自编号" clearable/>
        </FormItem>
        <FormItem label="车牌号" prop="carPlateNo">
          <i-input v-model="formData.carPlateNo" placeholder="请填写车牌号" />
        </FormItem>
        <FormItem label="车牌颜色" prop="carPlateColor">
          <i-select v-model.number="formData.carPlateColor" style="width: 184px;" filterable placeholder="请选择车牌颜色" clearable >
            <Option :value="1">蓝色</Option>
            <Option :value="2">黄色</Option>
            <Option :value="3">黑色</Option>
            <Option :value="4">白色</Option>
            <Option :value="5">绿色</Option>
            <Option :value="93">黄绿色</Option>
            <Option :value="9">其他</Option>
          </i-select>
        </FormItem>
        <FormItem label="车架号" prop="frameNo">
          <i-input v-model="formData.frameNo" placeholder="请填写车架号" clearable/>
        </FormItem>
        <FormItem label="发动机号" prop="vehicleEngineNo">
          <i-input v-model="formData.vehicleEngineNo" placeholder="请填写发动机号" clearable/>
        </FormItem>
        <FormItem label="营运证号" prop="vehicleOperationCertificateNo">
          <i-input v-model="formData.vehicleOperationCertificateNo" placeholder="请填写营运证号" clearable/>
        </FormItem>
        <FormItem label="运输企业" prop="deptUuid">
          <i-select v-model="formData.deptUuid" filterable placeholder="请选择运输企业" clearable :label-in-value="true" @on-change="enterpriseGroup">
            <Option v-for="item in subDeptList" :value="item.uuid" :key="item.uuid">{{ item.deptName }}</Option>
          </i-select>
        </FormItem>
        <FormItem label="归属部门" prop="inOrgUuid">
          <i-select v-model="formData.inOrgUuid" placeholder="请选择归属部门" clearable>
            <Option v-for="item in departmentList" :value="item.uuid" :key="item.uuid">{{ item.inOrgName }}</Option>
          </i-select>
        </FormItem>
        <FormItem label="车辆类型" prop="vehicleType">
          <i-input v-model="formData.vehicleType" placeholder="请填写车辆类型" clearable/>
        </FormItem>
        <FormItem label="车主/业户" prop="vehicleOwnerName">
          <i-input v-model="formData.vehicleOwnerName" placeholder="请填写车主/业户" clearable/>
        </FormItem>
        <FormItem label="车主电话" prop="vehicleOwnerPhone">
          <i-input v-model="formData.vehicleOwnerPhone" placeholder="请填写车主电话" clearable/>
        </FormItem>
        <FormItem label="车主住址">
          <i-input v-model="formData.vehicleOwnerAddress" placeholder="请输入车主住址" clearable />
        </FormItem>
        <FormItem label="联系人" prop="vehicleContactsName">
          <i-input v-model="formData.vehicleContactsName" placeholder="请填写联系人" clearable/>
        </FormItem>
        <FormItem label="联系电话" prop="vehicleContactsPhone">
          <i-input v-model="formData.vehicleContactsPhone" placeholder="请填写联系电话" clearable/>
        </FormItem>
        <FormItem label="家庭住址">
          <i-input v-model="formData.vehicleContactsAddress" placeholder="请输入家庭住址" clearable />
        </FormItem>
        <FormItem label="实际住址">
          <i-input v-model="formData.vehicleContactsLocation" placeholder="请输入实际住址" clearable />
        </FormItem>
        <FormItem label="初登日期" prop="wzVehicleDrivingPermitRegisterDate">
          <DatePicker type="date" v-model="formData.wzVehicleDrivingPermitRegisterDate" placeholder="请选择初登日期" clearable></DatePicker>
        </FormItem>
        <FormItem label="发证日期" prop="vehicleDrivingPermitIssueDate">
          <DatePicker type="date" v-model="formData.vehicleDrivingPermitIssueDate" placeholder="请选择发证日期" clearable></DatePicker>
        </FormItem>
        <FormItem label="到期日期" prop="vehicleDrivingPermitExpireDate">
          <DatePicker type="date" v-model="formData.vehicleDrivingPermitExpireDate" placeholder="请选择到期日期" clearable></DatePicker>
        </FormItem>
      </Card>
      <Card dis-hover :bordered="true" style="margin:0 0 10px;">
        <p slot="title">详细信息</p>
        <FormItem label="车辆品牌" prop="vehicleBrand">
          <i-input v-model="formData.vehicleBrand" placeholder="请填写车辆品牌" clearable/>
        </FormItem>
        <FormItem label="车辆型号" prop="vehicleModel">
          <i-input v-model="formData.vehicleModel" placeholder="请填写车辆型号" clearable/>
        </FormItem>
        <FormItem label="燃料类型" prop="fuelType">
          <i-select v-model="formData.fuelType" filterable placeholder="请选择燃料类型" clearable>
            <Option :value="item.value" v-for="item in fuelType" :key="item.value">{{item.value}}</Option>
          </i-select>
        </FormItem>
        <FormItem label="排放标准" prop="vehicleEmissionStandards">
          <i-select v-model="formData.vehicleEmissionStandards" filterable placeholder="请选择排放标准" clearable>
            <Option value="国Ⅳ">国Ⅳ</Option>
            <Option value="国Ⅴ">国Ⅴ</Option>
            <Option value="国Ⅵ">国Ⅵ</Option>
          </i-select>
        </FormItem>
        <FormItem label="核定总质量" prop="vehicleWeight">
          <i-input v-model="formData.vehicleWeight" placeholder="请填写核定总质量" clearable/>
        </FormItem>
        <FormItem label="核定载质量" prop="vehiclePermitWeight">
          <i-input v-model="formData.vehiclePermitWeight" placeholder="请填写核定载质量" clearable/>
        </FormItem>
        <FormItem label="准牵引质量" prop="vehicleTowWeight">
          <i-input v-model="formData.vehicleTowWeight" placeholder="请填写准牵引质量" clearable/>
        </FormItem>
        <FormItem label="备注" style="width:100%;">
          <i-input v-model="formData.remark" placeholder="请填写备注" type="textarea" :autosize="{minRows: 5,maxRows: 5}"/>
        </FormItem>
      </Card>
      <Card dis-hover :bordered="true" style="margin:0 0 10px;">
        <p slot="title">相关照片</p>
        <FormItem label="车头照片">
          <Upload :before-upload="vehicleImgFileFun" action="" style="color: #2d8cf0;cursor: pointer;">上传车头照片
          </Upload>
          <div class="demo-upload-list">
            <viewer style="width: 100%;height: 100%;">
              <img :src="!!vehicleImgData.url?vehicleImgData.url:'../../static/img/zwtpxd.png'" @error="public.imgDispose">
            </viewer>
          </div>
        </FormItem>

        <FormItem label="行驶证照片">
          <Upload :before-upload="vehicleLicenseImgFileFun" action="" style="color: #2d8cf0;cursor: pointer;">上传行驶证照片
          </Upload>
          <div class="demo-upload-list">
            <viewer style="width: 100%;height: 100%;">
              <img :src="!!vehicleLicenseImgData.url?vehicleLicenseImgData.url:'../../static/img/zwtpxd.png'" @error="public.imgDispose">
            </viewer>
          </div>
        </FormItem>
        <FormItem label="营运证照片">
          <Upload :before-upload="vehicleOperationCertificateImgFileFun" action="" style="color: #2d8cf0;cursor: pointer;">上传营运证照片
          </Upload>
          <div class="demo-upload-list">
            <viewer style="width: 100%;height: 100%;">
              <img :src="!!vehicleOperationCertificateImgData.url?vehicleOperationCertificateImgData.url:'../../static/img/zwtpxd.png'" @error="public.imgDispose">
            </viewer>
          </div>
        </FormItem>

        <FormItem label="车辆资料" style="width:100%;">
          <Upload action="*" :show-upload-list="false" :format="['jpg','jpeg','png']" :before-upload="handleBeforeUpload" multiple>
            <Button icon="ios-cloud-upload-outline">选择要上传的图片</Button>
          </Upload>
          <div style="margin:10px 0 0 0;padding: 10px;min-height: 220px;border: 1px solid #e1e1e1;">
            <!---->
            <div style="width: 200px;overflow: hidden;display: inline-block;margin-right: 4px;" v-for="item,index in imgEntityList">
              <div class="demo-upload-list">
                <img :src="item.imgUrl" @error="public.imgDispose">
                <div class="demo-upload-list-cover">
                  <Icon type="ios-eye-outline" @click.native="handleView(item.imgUrl)"></Icon>
                  <Icon type="ios-trash-outline" @click.native="imgEntityListRemove(item,index)"></Icon>
                </div>
              </div>
              <i-input v-model="item.imgName" placeholder="填写图片名称" @on-change="alterImgName(item)" clearable />
            </div>
            <div style="width: 200px;overflow: hidden;display: inline-block;margin-right: 4px;" v-for="item,index in defaultList">
              <div class="demo-upload-list">
                <img :src="item" @error="public.imgDispose">
                <div class="demo-upload-list-cover">
                  <Icon type="ios-eye-outline" @click.native="handleView(item)"></Icon>
                  <Icon type="ios-trash-outline" @click.native="handleRemove(item,index)"></Icon>
                </div>
              </div>
              <i-input v-model="nameList[index]" placeholder="填写图片名称" clearable />
            </div>
          </div>
        </FormItem>
      </Card>

      <div class="demo-drawer-footer">
        <Button style="margin-right: 8px" @click="$emit('closeFun', false)">取消</Button>
        <Button type="primary" @click="addSubmit('formAdd')">提交</Button>
      </div>
    </Form>

    <Spin size="large" fix v-if="spinShow"></Spin>

  </div>
</template>
<script>
  export default {
    // 需要修改的数据  表单类型  打开方式
    props: ["selectData"],//接收来自父组件的数据
    data() {
      return {
        spinShow:false,//本页加载
        uploadProgress: 0,//文件上传进度
        formData: {},//表单数据
        fuelType:[],//燃油类型
        ruleValidate: {//正则
          carPlateNo: [
            {required: true, message: '请填写车牌号', trigger: 'blur'},
            {
              validator: (rule, value, callBack) => {
                if (/^([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[a-zA-Z](([DF]((?![IO])[a-zA-Z0-9](?![IO]))[0-9]{4})|([0-9]{5}[DF]))|[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1})$/.test(value)) {
                  callBack()
                } else {
                  callBack('请正确填写车牌号')
                }
              }, trigger: 'blur'
            }
          ],
          frameNo: [
            {required: true, message: '请填写车架号', trigger: 'blur'}
          ],
          vehicleType: [
            {required: true, message: '请填写车辆类型', trigger: 'blur'}
          ],
          carPlateColor: [
            {type: "number", required: true, message: '请选择车牌颜色', trigger: 'blur'}
          ],
          wzVehicleDrivingPermitRegisterDate: [
            {type: "date", required: true, message: '请选择初登日期', trigger: 'blur'}
          ],
          deptUuid: [
            {required: true, message: '请选择运输企业', trigger: 'blur'}
          ],
          vehicleOwnerName: [
            {required: true, message: '请填写车主业户', trigger: 'blur'}
          ],
          vehicleOwnerPhone: [
            {required: true, message: '请填写车主业户电话', trigger: 'blur'},
            {
              validator: (rule, value, callBack) => {
                if (/^[1][0-9]{10}$/.test(value) || /^([0-9]{3,4}-)?[0-9]{7,8}$/.test(value)) {
                  callBack()
                } else {
                  callBack('请输入手机号 或者 区号-座机号')
                }
              }, trigger: 'blur'
            }
          ],
          vehicleContactsName: [
            {required: true, message: '请填写联系人', trigger: 'blur'}
          ],
          vehicleContactsPhone: [
            {required: true, message: '请填写联系人电话', trigger: 'blur'},
            {
              validator: (rule, value, callBack) => {
                if (/^[1][0-9]{10}$/.test(value) || /^([0-9]{3,4}-)?[0-9]{7,8}$/.test(value)) {
                  callBack()
                } else {
                  callBack('请输入手机号 或者 区号-座机号')
                }
              }, trigger: 'blur'
            }
          ],
        },

        emissionStandards: [],//排放标准
        //多图添加
        defaultList: [],//图片展示数据
        defaultListData: [],//图片表单数据
        nameList: [],//图片名称

        //多图修改
        imgEntityList: [],//多图回显数据
        subDeptList: [],//运输企业
        vehicleImgData:{//车头照片
          data:null,
          url:'',
        },
        vehicleLicenseImgData:{//行驶证照片
          data:null,
          url:'',
        },
        vehicleOperationCertificateImgData:{//营运证照片
          data:null,
          url:'',
        },
        departmentList:[],//部门
      }
    },
    beforeCreate() {//beforeCreate创建前状态

    },
    created() {//created创建完毕状态
    },
    beforeMount() {//beforeMount挂载前状态   DOM 元素然后塞入页面的过程

    },
    mounted() {//mounted 挂载结束状态
      let that = this;


      //燃油类型
      that.axios.post(that.apiUrl.systemDictSystemDictList, {type: 'fuel_type'}).then(res => {
        if (!!res) {
          that.fuelType = res.data.data;
        }
      }).catch(err => {
        console.log('失败', err);
      })



      //运输企业
      that.axios.post(that.apiUrl.coreDeptCoreDeptList,{}).then(res => {
        if (!!res) {
          that.subDeptList = res.data.data;
          if (!that.selectData.id) {
            that.$set(that.formData, 'deptUuid', that.subDeptList[0].uuid)//赋值
            that.$set(that.formData, 'deptName', that.subDeptList[0].deptName)//赋值
            that.enterpriseGroup({label: that.subDeptList[0].deptName,value: that.subDeptList[0].uuid})
          }
        }
      }).catch(err => {
        console.log("失败", err)
      })




      if (!that.selectData.id) {
        // that.formData.govState = 1;//表单
      } else {
        that.formData = JSON.parse(JSON.stringify(that.selectData));//表单
        that.enterpriseGroup({label: that.formData.deptName,value: that.formData.deptUuid})

        if(!!that.formData.vehicleImg){//车头照片
          that.$set(that.vehicleImgData, 'url', that.apiUrl.imgUrl + that.formData.vehicleImg)//赋值
        }
        if(!!that.formData.vehicleLicenseImg){//行驶证照片
          that.$set(that.vehicleLicenseImgData, 'url', that.apiUrl.imgUrl + that.formData.vehicleLicenseImg)//赋值
        }
        if(!!that.formData.vehicleOperationCertificateImg){//营运证照片
          that.$set(that.vehicleOperationCertificateImgData, 'url', that.apiUrl.imgUrl + that.formData.vehicleOperationCertificateImg)//赋值
        }

        //车辆修改详情
        that.spinShow = true;
        that.axios.post(that.apiUrl.coreVehicleCoreVehicleInfo, {uuid: that.formData.uuid}).then(res => {
          if (!!res) {
            var data = res.data.data;
            data.wzVehicleDrivingPermitRegisterDate = !!data.vehicleDrivingPermitRegisterDate ? new Date(data.vehicleDrivingPermitRegisterDate):'';
            that.formData = data;//表单
            let imgList = [];
            res.data.data.coreVehicleImgList.forEach((k, i) => {
              k.imgUrl = that.apiUrl.imgUrl + k.imgUrl
              imgList.push(k);
            })

            that.imgEntityList = imgList;//res.data.data;//多图回显
            that.$set(that.formData, 'imgUpdateListStr',[])//赋值
            that.$set(that.formData, 'imgDeleteIdListStr',[])//赋值
            that.spinShow = false;
          }
        }).catch(err => {
          console.log("失败", err)
        })
      }


    },
    methods: {//执行的方法
      //部门级联
      enterpriseGroup(data){
        let that = this;
        if(!!data){
          that.$set(that.formData, 'deptName', data.label)//赋值
          //部门
          that.axios.post(that.apiUrl.coreInOrgCoreInOrgList,{deptUuid:that.formData.deptUuid,inOrgType:2}).then(res => {
            if (!!res) {
              that.departmentList = res.data.data;
            }
          }).catch(err => {
            console.log("失败", err)
          })
        }else{
          that.departmentList = [];
          that.$set(that.formData, 'inOrgUuid', '')//赋值
          that.$set(that.formData, 'deptName', '')//赋值
        }
      },
      vehicleImgFileFun(file) {//车头照片
        let that = this;
        let type = file.type.split("/")[0];
        if (type == "image") {//图片
          that.$set(that.vehicleImgData, 'url',window.URL.createObjectURL(file))//赋值
          that.$set(that.vehicleImgData, 'data',file)//赋值
        } else {
          that.$Message.warning('请选择jpg、png、jpeg的图片进行上传');
        }
        return false;
      },
      vehicleLicenseImgFileFun(file) {//行驶证照片
        let that = this;
        let type = file.type.split("/")[0];
        if (type == "image") {//图片
          that.$set(that.vehicleLicenseImgData, 'url',window.URL.createObjectURL(file))//赋值
          that.$set(that.vehicleLicenseImgData, 'data',file)//赋值
        } else {
          that.$Message.warning('请选择jpg、png、jpeg的图片进行上传');
        }
        return false;
      },
      vehicleOperationCertificateImgFileFun(file) {//营运证照片
        let that = this;
        let type = file.type.split("/")[0];
        if (type == "image") {//图片
          that.$set(that.vehicleOperationCertificateImgData, 'url',window.URL.createObjectURL(file))//赋值
          that.$set(that.vehicleOperationCertificateImgData, 'data',file)//赋值
        } else {
          that.$Message.warning('请选择jpg、png、jpeg的图片进行上传');
        }
        return false;
      },
      //提交表单
      addSubmit(data) {
        let that = this;
        that.$refs[data].validate((valid) => {
          if (valid) {//正则判断使用
            let data = JSON.parse(JSON.stringify(that.formData));
            delete  data.coreVehicleImgList;
            let formData = new FormData();
            //车辆资料
            that.defaultListData.forEach(function (k, i) {
              let type = k.name.substr((k.name.lastIndexOf(".") + 1));
              formData.append('imgList', k, (that.nameList[i].length > 0 ? that.nameList[i] : '图片描述') + '.' + type);
            })


            //行驶证初登日期
            data.vehicleDrivingPermitRegisterDate = (!!data.wzVehicleDrivingPermitRegisterDate) ? that.public.timeFormatting(data.wzVehicleDrivingPermitRegisterDate, "yyyy-MM-dd") : '';
            //发证日期
            data.vehicleDrivingPermitIssueDate = (!!data.vehicleDrivingPermitIssueDate) ? that.public.timeFormatting(data.vehicleDrivingPermitIssueDate, "yyyy-MM-dd") : '';
            //到期日期
            data.vehicleDrivingPermitExpireDate = (!!data.vehicleDrivingPermitExpireDate) ? that.public.timeFormatting(data.vehicleDrivingPermitExpireDate, "yyyy-MM-dd") : '';



            if (!!data.imgUpdateListStr) {
              if (data.imgUpdateListStr instanceof Object) {
                data.imgUpdateListStr = JSON.stringify(data.imgUpdateListStr);
              }
            }
            delete data.imgEntityList;
            delete data.vehicleEnvironmentalProtectionImg;
            delete data.vehicleQualityCertificateImg;


            for (let key in data) {
              // if (!!data[key]) {
                formData.append(key, data[key]);
              // }
            }



            if(!!that.vehicleImgData.data){//车头照片
              formData.append('vehicleImgFile', that.vehicleImgData.data);
            }
            if(!!that.vehicleLicenseImgData.data){//行驶证照片
              formData.append('vehicleLicenseImgFile', that.vehicleLicenseImgData.data);
            }
            if(!!that.vehicleOperationCertificateImgData.data){//营运证照片
              formData.append('vehicleOperationCertificateImgFile', that.vehicleOperationCertificateImgData.data);
            }


            that.axios.post(that.apiUrl.coreVehicleCoreVehicleSaveOrUpdate, formData, that.public.parameterUploadProgress(that)).then(res => {
              that.$Spin.hide();
              if (!!res) {
                that.$Message.success("保存成功");
                that.$emit("closeFun", true)
              }
            }).catch(err => {
              console.log('失败', err);
            })
          } else {
            that.$Message.error('请正确填写表单');
          }
        })
      },
      //缩略图查看
      handleView(src) {
        let imgUrls = [];
        imgUrls.push(src)
        this.$viewerApi({
          images: imgUrls
        })
      },
      //多图回显删除
      imgEntityListRemove(data, index) {
        this.formData.imgDeleteIdListStr.push(data.uuid);
        this.imgEntityList.splice(index, 1);
      },
      //车辆资料删除
      handleRemove(file, index) {//新添加的图片删除
        this.defaultList.splice(index, 1);
        this.defaultListData.splice(index, 1);
        this.nameList.splice(index, 1);
      },
      handleBeforeUpload(file) {//新增的时候 处理图片数据
        //如果是文件  就展示文件名
        let type = file.type.split("/")[0];
        if (type == "image") {//图片
          this.defaultList.push(window.URL.createObjectURL(file));
          this.defaultListData.push(file);
          this.nameList.push("图片描述");
        } else {
          this.$Message.error('请选择jpg、png、jpeg的图片进行上传');
        }
        return false;
      },
      //运输企业
      deptNameFun(e) {
        if (!!e) {
          this.formData.deptName = e.label;
        } else {
          this.formData.deptName = "";
        }
      },
      //回显图片备注被修改的时候
      alterImgName(data) {
        let that = this;
        let type = true;
        that.formData.imgUpdateListStr.forEach((k, i) => {
          if (k.uuid == data.uuid) {//存在相同数据
            k.imgName = (data.imgName.length > 0 ? data.imgName : "图片描述");
            type = false;
            return false;
          }
        })
        if (type) {
          that.formData.imgUpdateListStr.push({
            'uuid': data.uuid,
            imgName: (data.imgName.length > 0 ? data.imgName : "图片描述")
          });
        }
      },

    },
    watch: {//监听

    },
    beforeUpdate() {//beforeUpdate 更新前状态

    },
    updated() {//updated 更新完成状态

    },
    beforeDestroy() {//beforeDestroy 销毁前状态

    },
    destroyed() {//destroyed 销毁完成状态

    }
  }
</script>
<style lang="less">
  ._wz_transportVehicleAdd {

    .demo-upload-list {
      display: inline-block;
      width: 200px;
      height: 140px;
      text-align: center;
      line-height: 140px;
      border-radius: 4px;
      overflow: hidden;
      background: #fff;
      position: relative;
      border: 1px solid rgba(0, 0, 0, .2);
      margin-right: 4px;

      img {
        width: 100%;
        height: 100%;
      }

      .demo-upload-list-cover {
        display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0, 0, 0, .6);

        i {
          color: #fff;
          font-size: 40px;
          cursor: pointer;
          margin: 0 2px;
        }
      }
    }

    .demo-upload-list:hover .demo-upload-list-cover {
      display: block;
    }

  }


</style>
